package git.soulbgm.common.redis.serializer;

import git.soulbgm.utils.ProtostuffUtil;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * protostuff序列化
 *
 * @author SoulBGM
 * @date 2024/02/29
 */
public class ProtostuffSerializer implements RedisSerializer<Object> {
    @Override
    public byte[] serialize(Object t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return ProtostuffUtil.serializer(new UniversalPojo<>(t));
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        UniversalPojo<Object> pojo = ProtostuffUtil.deserializer(bytes, UniversalPojo.class);
        return pojo.getT();
    }

    /**
     * 通用实体
     *
     * @author SoulBGM
     * @date 2024/02/29
     */
    public static class UniversalPojo<T> {
        private T t;

        public UniversalPojo() {
        }

        public UniversalPojo(T t) {
            this.t = t;
        }

        public T getT() {
            return t;
        }
    }
}
